package com.guli.mall.pms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.common.constant.ProductAttrTypeEnum;
import com.guli.common.constant.ProductEnum;
import com.guli.common.utils.CopyPageProperties;
import com.guli.mall.pms.entity.AttrAttrgroupRelationEntity;
import com.guli.mall.pms.entity.AttrGroupEntity;
import com.guli.mall.pms.entity.vo.AttrGroupAndAttrVo;
import com.guli.mall.pms.entity.vo.AttrVo;
import com.guli.mall.pms.feign.ProductCategoryFeignClient;
import com.guli.mall.pms.service.AttrAttrgroupRelationService;
import com.guli.mall.pms.service.AttrGroupService;
import com.guli.mall.serviceBase.globalException.MallException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.mall.pms.mapper.AttrMapper;
import com.guli.mall.pms.entity.AttrEntity;
import com.guli.mall.pms.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrMapper, AttrEntity> implements AttrService {

    @Resource
    ProductCategoryFeignClient productCategoryFeignClient;

    @Resource
    AttrGroupService attrGroupService;

    @Resource
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils<AttrVo> queryPage(Integer currentPage, Integer size, AttrEntity attrEntity) {

        Page<AttrEntity> page = new Page<>(currentPage, size);

        QueryWrapper<AttrEntity> wrapper = null;

        if (!ObjectUtils.isEmpty(attrEntity)) {
            wrapper = new QueryWrapper<AttrEntity>();
            if (!ObjectUtils.isEmpty(attrEntity.getCatelogId())) {
                wrapper.eq("catelog_id", attrEntity.getCatelogId());
            }
            if (!StringUtils.isEmpty(attrEntity.getAttrName())) {
                wrapper.like("attr_name", attrEntity.getAttrName());
            }
            if (!ObjectUtils.isEmpty(attrEntity.getAttrId())) {
                wrapper.eq("attr_id", attrEntity.getAttrId());
            }
            if (!ObjectUtils.isEmpty(attrEntity.getAttrType())) {
                wrapper.eq("attr_type", attrEntity.getAttrType());
            }

        }
        Page<AttrEntity> resultPage = this.page(page, wrapper);

        // 拷贝以及赋值
        Page<AttrVo> attrVoPage = CopyPageProperties.copy(resultPage, AttrVo.class);

        for (AttrVo attrVo : attrVoPage.getRecords()) {
            /**
             * 查询属性的categoryName
             * */
            String categoryName = productCategoryFeignClient.getCategoryName(attrVo.getCatelogId());

            attrVo.setCategoryName(categoryName);

            // 如果是销售属性，就不查询其attr-group-relation
            if (attrVo.getAttrType().equals(ProductAttrTypeEnum.SELL_ATTRIBUTE.getAttrType())) {
                continue;
            }
            /**
             * 查询属性的 attr_attrgroup_relation 属性-属性分组关系表 查询到所属分组 attrGroupId
             * 再根据 attrGroupId 再 attr-group 表中查询到对应的 attrGroupName
             * */
            AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getAttrGroupRelationByAttrId(attrVo.getAttrId());

            // 根据 attr_attrgroup_relation 中的 attrGroupId 查询 attrGroupName
            if (!ObjectUtils.isEmpty(relation)) {

                AttrGroupEntity byId = attrGroupService.getById(relation.getAttrGroupId());

                if (!ObjectUtils.isEmpty(byId)) {
                    attrVo.setAttrGroupName(byId.getAttrGroupName());

                    attrVo.setAttrGroupId(byId.getAttrGroupId());
                } else {
                    attrVo.setCategoryName("该属性没有设置分组");
                }


            } else {
                String warn = "属性：" + attrVo.getAttrName() + "在 attr_attrgroup_relation 表中没有与 attr-group表建立关系";
                log.warn(warn);
                attrVo.setAttrGroupName(warn);
            }

        }


        return new PageUtils<>(attrVoPage);
    }

    @Override
    public AttrVo getAttrAndAttrGroupIdById(Long attrId) {

        AttrEntity byId = this.getById(attrId);

        AttrVo attrVo = new AttrVo();

        BeanUtils.copyProperties(byId, attrVo);

        AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getAttrGroupRelationByAttrId(attrId);

        if (!ObjectUtils.isEmpty(relation)) {
            attrVo.setAttrGroupId(relation.getAttrGroupId());

            attrVo.setAttrSort(relation.getAttrSort());
        } else {
            attrVo.setAttrGroupName("该属性没有设置属性分组");
        }


        return attrVo;
    }

    @Transactional
    @Override
    public void updateByIdAndUpdateRelation(AttrVo attr) {

        this.updateById(attr);

        /**
         * 只有是基本类型才更新 attr-group-relation
         * */
        if (ProductAttrTypeEnum.BASIC_ATTRIBUTE.getAttrType().equals(attr.getAttrType())) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();

            relation.setAttrId(attr.getAttrId());

            relation.setAttrGroupId(attr.getAttrGroupId());

            relation.setAttrSort(attr.getAttrSort());

            attrAttrgroupRelationService.updateByAttrId(relation);
        }


    }

    @Transactional
    @Override
    public void insertAttrAndRelation(AttrVo attr) {

        this.save(attr);

        if (attr.getAttrType().equals(ProductAttrTypeEnum.BASIC_ATTRIBUTE.getAttrType())) {
            /**
             * 是基本属性才添加 attr-group-relation
             * */
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrId(attr.getAttrId());

            relationEntity.setAttrSort(attr.getAttrSort());

            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            attrAttrgroupRelationService.save(relationEntity);
        }


    }

    @Override
    public List<AttrEntity> listByIdsAndOtherCondition(List<Long> attrIdList, AttrEntity attrEntity) {


        // 是否只获取基本属性【true：只获取基本属性；false：只获取销售属性】
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = attrEntityQueryWrapper = new QueryWrapper<>();

        if (!ObjectUtils.isEmpty(attrEntity)) {

            if (!ObjectUtils.isEmpty(attrEntity.getAttrType())) {

                attrEntityQueryWrapper.eq("attr_type", attrEntity.getAttrType());

            }
        }

        attrEntityQueryWrapper.in("attr_id", attrIdList);

        return this.list(attrEntityQueryWrapper);
    }

    @Override
    public List<AttrEntity> getAttrByCategoryIdAndCondition(Long categoryId, AttrEntity attrEntity) {

        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();

        attrEntityQueryWrapper.eq("catelog_id", categoryId);

        if (!ObjectUtils.isEmpty(attrEntity)) {
            if (!ObjectUtils.isEmpty(attrEntity.getAttrType())) {
                attrEntityQueryWrapper.eq("attr_type", attrEntity.getAttrType());
            }
        }

        List<AttrEntity> list = this.list(attrEntityQueryWrapper);

        return list;
    }

    @Override
    public List<AttrEntity> getAttrByCategoryIdAndFilterNonSearchType(Long catalogId) {

        List<AttrEntity> attrByCategoryIdAndCondition = getAttrByCategoryIdAndCondition(catalogId, null);

        return attrByCategoryIdAndCondition.stream().filter(attr -> {
            // 只保留需要索引的属性
            return attr.getSearchType() == ProductEnum.SearchType.NEED.getType();

        }).collect(Collectors.toList());
    }


}